package com.pri.chat.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.entity.MessageBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.DialogCommentAdapter;
import com.pri.chat.adapter.VideoListAdapter;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.DTModel;
import com.pri.chat.model.EvaListModel;
import com.pri.chat.model.MessageModel;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.ScrollCalculatorHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxImageTool;
import com.vondear.rxtool.view.RxToast;
import com.yc.pagerlib.recycler.OnPagerListener;
import com.yc.pagerlib.recycler.PagerLayoutManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author
 * @time 2020/4/29
 */
public class MyVideoActivity extends AppCompatActivity implements BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.iv_return)
    ImageView backBtn;
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    Dialog mCommentDialog;
    PagerLayoutManager viewPagerLayoutManager;
    ScrollCalculatorHelper mscrollCalculatorHelper;
    private String otherMemberId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_video_layout);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        otherMemberId = bundle.getString("id");
        initView();
    }


    protected void initView() {
        initLayout();
        initScroll();
        initSrl();
        initData();
        initCommentDialog();
    }

    private int type;
    private List<MessageBean> mCommentList = new ArrayList<>();
    private RecyclerView mRvComment;
    private DialogCommentAdapter mCommentAdapter;
    private ImageView mIvClose, mIvNone;
    private LinearLayout ll_huifu;
    private List<DTBean> mList;
    private VideoListAdapter mAdapter;
    private boolean isShowDialog = true;
    private int page = 1;
    private int comment_page = 1;
    private SmartRefreshLayout mSrlComment;
    private EditText mEtInput;
    private TextView mTvSendMessage;
    private int mPosition;


    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }


    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }

    private void refresh() {
        mList.clear();
        mAdapter.notifyDataSetChanged();
        page = 1;
        isShowDialog = false;
        initData();
    }


    /**
     * 初始化视频布局
     */
    private void initLayout() {
        mList = new ArrayList<>();
        viewPagerLayoutManager = new PagerLayoutManager(
                this, OrientationHelper.VERTICAL);
        recMain.setLayoutManager(viewPagerLayoutManager);
        mAdapter = new VideoListAdapter(R.layout.item_video, mList);
        mAdapter.setOnItemChildClickListener(this);
        recMain.setAdapter(mAdapter);
        viewPagerLayoutManager.setOnViewPagerListener(new OnPagerListener() {
            @Override
            public void onInitComplete() {
                System.out.println("OnPagerListener---onInitComplete--" + "初始化完成");
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                System.out.println("OnPagerListener---onPageRelease--" + position + "-----" + isNext);
                BaseViewHolder holder = (BaseViewHolder) recMain.findViewHolderForLayoutPosition(position);
                ImageView imageFengMian = holder.getView(R.id.imageFengMian);
                imageFengMian.animate().alpha(1).setDuration(1000).start();
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                System.out.println("OnPagerListener---onPageSelected--" + position + "-----" + isBottom);
            }
        });
//        recMain.setRecyclerListener(new RecyclerView.RecyclerListener() {
//            @Override
//            public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
//                VideoPlayer videoPlayer = ((VideoAdapter.VideoViewHolder) holder).mVideoPlayer;
//                if (videoPlayer == VideoPlayerManager.instance().getCurrentVideoPlayer()) {
//                    VideoPlayerManager.instance().releaseVideoPlayer();
//                }
//            }
//        });
    }

    /**
     * 视频滑动相关
     */
    private void initScroll() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mscrollCalculatorHelper = new ScrollCalculatorHelper(R.id.detail_player
                , dm.heightPixels / 2 - RxImageTool.dip2px(180)
                , dm.heightPixels / 2 + RxImageTool.dip2px(180));
        recMain.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                mscrollCalculatorHelper.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = viewPagerLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = viewPagerLayoutManager.findLastVisibleItemPosition();
                //大于0说明有播放
                mscrollCalculatorHelper.onScroll(recyclerView, firstVisibleItem, lastVisibleItem, 1);
            }
        });
    }


    private void initCommentDialog() {
        mCommentDialog = new Dialog(this, R.style.Theme_Light_Dialog);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_comment, null);
        mSrlComment = dialogView.findViewById(R.id.srl_comment);
        mRvComment = dialogView.findViewById(R.id.rec_comment);
        mIvClose = dialogView.findViewById(R.id.iv_close);
        mIvNone = dialogView.findViewById(R.id.iv_none);
        mTvSendMessage = dialogView.findViewById(R.id.tv_send_message);
        mEtInput = dialogView.findViewById(R.id.et_input);
        ll_huifu = dialogView.findViewById(R.id.ll_huifu);
        ll_huifu.setVisibility(View.VISIBLE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRvComment.setLayoutManager(linearLayoutManager);
        mRvComment.setNestedScrollingEnabled(false);
        mCommentAdapter = new DialogCommentAdapter(R.layout.item_message, mCommentList);
        mRvComment.setAdapter(mCommentAdapter);
        //获得dialog的window窗口
        Window window = mCommentDialog.getWindow();
        WindowManager wm = this.getWindowManager();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出

        window.setWindowAnimations(R.style.dialogStyle);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = 1200;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        mCommentDialog.setContentView(dialogView);
        initListener();
        mCommentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_logo:
                        if (mCommentList.get(position).getMemberId().equals(SharedHelper.readId(MyVideoActivity.this))) {
                            RxActivityTool.skipActivity(MyVideoActivity.this, PeopleMsgActivity.class);
                            break;
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", mCommentList.get(position).getMemberId());
                            RxActivityTool.skipActivity(MyVideoActivity.this, OtherPeopleMsgActivity.class, bundle);
                            break;
                        }
                }
            }
        });
    }

    private void initListener() {
        mSrlComment.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(1500);
            refreshCommentList(false);
        });
        mSrlComment.setOnLoadmoreListener(refreshlayout -> {
            refreshlayout.finishLoadmore(1500);
            comment_page++;
            isShowDialog = false;
            httpGetComment(mPosition, false);
        });
        mTvSendMessage.setOnClickListener(view -> {
            if (mEtInput.getText().toString().isEmpty()) {
                RxToast.normal(mEtInput.getHint().toString());
                return;
            }
            httpSendMessage(mPosition);
        });
        mIvClose.setOnClickListener(view -> {
            mCommentDialog.dismiss();
        });

    }

    private void refreshCommentList(boolean s) {
        comment_page = 1;
        mCommentList.clear();
        mCommentAdapter.notifyDataSetChanged();
        isShowDialog = false;
        httpGetComment(mPosition, s);
    }

    private void httpGetComment(int pos, boolean isShowComment) {
        SubscriberOnNextListener<BaseBean<List<MessageBean>>> onNextListener = baseBean -> {
            if (isShowComment) {
                mCommentDialog.show();
            }
            if (baseBean.getData().isEmpty() && comment_page == 1) {
                mIvNone.setVisibility(View.VISIBLE);
                mCommentAdapter.notifyDataSetChanged();

            } else {
                mIvNone.setVisibility(View.INVISIBLE);
                mCommentList.addAll(baseBean.getData());
                mCommentAdapter.notifyDataSetChanged();
            }
        };

        EvaListModel evaListModel = new EvaListModel();
        evaListModel.setPageIndex(comment_page);
        evaListModel.setObjId(mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(evaListModel));
        HttpMethods.getInstance().listPingLun(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    private void httpSendMessage(int pos) {
        HideSoftInput(ll_huifu.getWindowToken());
        SubscriberOnNextListener<BaseBean<List<MessageBean>>> onNextListener = baseBean -> {
            RxToast.normal("评论成功");
            mEtInput.setText("");
            refreshCommentList(false);

        };
        Gson gson = new Gson();
        MessageModel circleEnity = new MessageModel();
        circleEnity.setType(0);
        circleEnity.setObjId(mList.get(pos).getId());
        circleEnity.setMemberId(SharedHelper.readId(this));
        circleEnity.setContent(mEtInput.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(circleEnity));
        HttpMethods.getInstance().savePingLun(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    private boolean isShowGiftDialog = false;

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        mPosition = position;
        switch (view.getId()) {
            case R.id.shareLinear:
                initShareDialog(mList.get(mPosition).getVideoPath()+"?vframe/jpg/offset/1", position);
                break;
            case R.id.plLinear:
                refreshCommentList(true);
                break;
            case R.id.zanLinear:
                httpLike(position);
                break;
            case R.id.iv_logo:
                Bundle bundle = new Bundle();
                bundle.putString("id", mList.get(position).getMemberId());
                RxActivityTool.skipActivity(this, OtherPeopleMsgActivity.class, bundle);
                break;
        }
    }

    private Dialog mShareDialog;
    private void initShareDialog(String path, int pos) {
        String memberId = SharedHelper.readId(MyVideoActivity.this);
        String listMemberId = mList.get(pos).getMemberId();
        int type = 1;
        if (listMemberId.equals(memberId)) {
            type = 2;
        }
        mShareDialog = DialogUtil.getInstance().showShareDialog(MyVideoActivity.this, type);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("image",path);
                bundle.putString("title",mList.get(pos).getMemberName());
                bundle.putString("content",mList.get(pos).getContent());
                RxActivityTool.skipActivity(MyVideoActivity.this, ShareMemberActivity.class,bundle);
                mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                mShareDialog.dismiss();
                //删除操作
                deleteDongTai(pos);
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("type","1");
                RxActivityTool.skipActivity(MyVideoActivity.this, ReleaseJuBaoAcctivity.class,bundle);
            }
        });
        mShareDialog.show();
    }


    private void deleteDongTai(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                RxToast.normal("删除成功！");
                mList.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        };

        Map<String, Object> params = new HashMap<>();
        params.put("id", mList.get(position).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteDongTai(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    private static final String TAG = "MyVideoActivity";

    private void httpLike(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            if (mList.get(pos).getSfdz() == 0) {
                mList.get(pos).setSfdz(1);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum() + 1);
            } else {
                mList.get(pos).setSfdz(0);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum() - 1);
            }
            mAdapter.refreshPartItem(pos);
            RxToast.normal(baseBean.getMsg());
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(mList.get(pos).getId());
        zanModel.setDzrId(SharedHelper.readId(this));
        zanModel.setType(1);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void initRv() {

    }

    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<DTBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                RxToast.normal(getString(R.string.no_data));
            } else {
                none.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                mAdapter.notifyDataSetChanged();
            }
        };
        String lat = SharedHelper.readValueByKeyForString(this, "lat");
        String lng = SharedHelper.readValueByKeyForString(this, "lng");
        DTModel dtModel = new DTModel(page, 1, SharedHelper.readId(this), lat, lng,"","");//登录上传参数
        dtModel.setSendMemberId(otherMemberId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().dt_list(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    @OnClick(R.id.iv_return)
    public void onViewClicked() {
        finish();
    }
}
